import { http } from './requestGitee'
export let dataId: string
const DataBaseDescription = 'GreenBoy网址导航数据库'

const defaultTags = [
  {
    key: 'quickoffice',
    name: '效率办公'
  },
  {
    key: 'zixunluntan',
    name: '资讯论坛'
  },
  {
    key: 'tool',
    name: '小工具'
  },
  {
    key: 'blog',
    name: '博客'
  },
  {
    key: 'code',
    name: '编程'
  },
  {
    key: 'frontend',
    name: '前端'
  },
  {
    key: 'gis',
    name: 'GIS'
  },
  {
    key: 'video',
    name: '视频'
  },
  {
    key: 'game',
    name: '游戏'
  },
  {
    key: 'netdisk',
    name: '网盘'
  },
  {
    key: 'doc',
    name: '文库'
  },
  {
    key: 'ec',
    name: '电商'
  },
  {
    key: 'music',
    name: '音乐'
  },
  {
    key: 'design',
    name: '设计'
  },
  {
    key: 'picture',
    name: '图片'
  },
  {
    key: 'browser',
    name: '浏览器增强'
  },
  {
    key: 'soft',
    name: '软件'
  },
  {
    key: 'system',
    name: '系统工具'
  },
  {
    key: 'yuancheng',
    name: '远程控制'
  },
  {
    key: 'tizi',
    name: '科学上网'
  },
  {
    key: 'guide',
    name: '网址导航'
  },
  {
    key: 'mobileapp',
    name: '手机app'
  },
  {
    key: 'money',
    name: '理财'
  },
  {
    key: 'resource',
    name: '资源'
  }
]

const createDataBase = () =>
  http
    .post('', {
      files: {
        sites: {
          content: JSON.stringify([], null, 2)
        },
        tags: {
          content: JSON.stringify(defaultTags, null, 2)
        }
      },
      description: DataBaseDescription
    })
    .then((dataBase: any) => {
      dataId = dataBase.id
      return JSON.parse(dataBase.files.sites.content)
    })
export const getData = async () => {
  const res: any[] = await http.get('')
  const dataBase = res.find((item) => item.description === DataBaseDescription)
  if (dataBase) {
    dataId = dataBase.id
    const files = dataBase.files

    const sites = JSON.parse(files.sites.content)

    //#region 2024.7.18 旧数据整理代码
    let old = false
    sites.forEach((item: any) => {
      if (item.iconify) {
        old = true
        item.ico ||= item.iconify
        item.iconify = void 0
      }
    })
    if (old) {
      setDataBase(sites, 'sites')
    }
    //#endregion

    let tags
    try {
      tags = JSON.parse(files.tags.content)
    } catch (error) {
      tags = defaultTags
      setDataBase(tags, 'tags')
    }

    return {
      sites,
      tags
    }
  } else {
    return createDataBase()
  }
}

export const setDataBase = (list: any[], filename: string) =>
  http.patch(dataId, {
    files: {
      [filename]: {
        content: JSON.stringify(list, null, 2)
      }
    }
  })
